#!/usr/bin/python3
# _*_ coding: utf-8 _*_
#
# Copyright (C) 2024 - 2024 heihieyouheihei, Inc. All Rights Reserved 
#
# @Time    : 2024/8/23 21:58
# @Author  : Yuyun
# @File    : leetcode_59_螺旋矩阵.py
# @IDE     : PyCharm

"""
给你一个正整数 n ，生成一个包含 1 到 n^2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

输入：n = 3
输出：[[1,2,3],[8,9,4],[7,6,5]]

输入：n = 1
输出：[[1]]

提示：
1 <= n <= 20
"""

class Solution:
    #定义四个边界，直接边界遍历数组，确认具体位置的值
    def Matrix_N(self, n):
        #初始化n * n矩阵
        matrix = [[0] * n for _ in range(n)]
        top, bottom, left, right = 0,  n - 1, 0, n - 1
        num = 1
        while top <= bottom and left <= right:

            #从左到右填充上边界
            for i in range(left, right + 1):
                matrix[top][i] = num
                num += 1
            top += 1
            #从上到下填充右边界
            for i in range(top, bottom + 1):
                matrix[i][right] = num
                num += 1
            right -= 1
            #从右到左填充下边界
            for i in range(right, left - 1, -1):        #逆向填充
                matrix[bottom][i] = num
                num += 1
            bottom -= 1
            #从下到上填充左边界
            for i in range(bottom, top - 1, -1):        #逆向填充
                matrix[i][left] = num
                num += 1
            left += 1
        return matrix

    #定义X、Y轴，再使用偏移量offset，遍历四个方向，确认具体位置的值
    def generateMatrix(self, n: int):
        nums = [[0] * n for _ in range(n)]
        startx, starty = 0, 0  # 起始点
        loop, mid = n // 2, n // 2  # 迭代次数、n为奇数时，矩阵的中心点
        count = 1  # 计数

        for offset in range(1, loop + 1):  # 每循环一层偏移量加1，偏移量从1开始
            for i in range(starty, n - offset):  # 从左至右，左闭右开
                nums[startx][i] = count
                count += 1
            for i in range(startx, n - offset):  # 从上至下
                nums[i][n - offset] = count
                count += 1
            for i in range(n - offset, starty, -1):  # 从右至左
                nums[n - offset][i] = count
                count += 1
            for i in range(n - offset, startx, -1):  # 从下至上
                nums[i][starty] = count
                count += 1
            startx += 1  # 更新起始点
            starty += 1

        if n % 2 != 0:  # n为奇数时，填充中心点
            nums[mid][mid] = count
        return nums

if __name__ == "__main__":
    n = int(input())
    solution = Solution()
    print(solution.Matrix_N(n))
